<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of utility
 *
 * @author tridungpham
 */
class Utility extends Object
{
    static function getSiteUrl()
    {
        $base_url = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http';
        $base_url .= '://' . $_SERVER['HTTP_HOST'];
        $base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);
        if(substr($base_url,-1,1) == '/')
            $base_url = substr($base_url,0,strlen($base_url) - 1);
        return $base_url;
    }

    static function redirect($url = NULL)
    {
        $target_url = Utility::getSiteUrl();        
        if (!is_null($url))
            $target_url .= "/" . $url;            
        header("Location: " . $target_url);
    }

    static function currentUrl()
    {
        $pageURL = 'http';
        if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on")
        {
            $pageURL .= "s";
        }
        $pageURL .= "://";
        if ($_SERVER["SERVER_PORT"] != "80")
        {
            $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
        }
        else
        {
            $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
        }

        if(substr($pageURL,-1,1) == '/')
            $pageURL = substr($pageURL,0,strlen($pageURL) - 1);
            return $pageURL;
    }

    static function error($errorMessage,$linkBack = NULL)
    {
        $session = Session::getInstance();
        $session->set('em',$errorMessage);
        $session->set('lb',$linkBack);
        self::redirect('error');
    }

    static function websiteRoot()
    {
        $pageURL = 'http';
        if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on")
        {
            $pageURL .= "s";
        }
        $pageURL .= "://";
        if ($_SERVER["SERVER_PORT"] != "80")
        {
            $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"];
        }
        else
        {
            $pageURL .= $_SERVER["SERVER_NAME"];
        }

        
        $arr = str_replace($_SERVER['DOCUMENT_ROOT'], '', $_SERVER['SCRIPT_FILENAME']);
        $arr = explode("/", $arr);
        if(count($arr) > 3)
            $pageURL .= '/' . $arr[1];

        if (substr($pageURL, -1, 1) == '/')
            $pageURL = substr($pageURL, 0, strlen($pageURL) - 1);
            
        return $pageURL;
    }

    static function baseUrl()
    {
        global $base_url;
        return $base_url;
    }
}

?>
